<template>
  <!-- 校区参训统计模块 -->
  <el-row :gutter="16" class="data-row">
    <el-col :span="24">
      <el-card class="data-card" shadow="never">
        <div slot="header" class="card-header">
          <div class="header-left">
            <i class="el-icon-s-custom" />
            <span>校区参训统计（统计正常状态的校区）</span>
          </div>
          <div class="header-right">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="培训开始日期" end-placeholder="培训结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" size="small" style="width: 300px; margin-right: 8px;" @change="handleDateRangeChange" />
            <el-select v-model="filterForm.brand" placeholder="请选择校区品牌" size="small" style="width: 120px; margin-right: 8px;" @change="handleFilterChange" :class="{ 'is-error': !filterForm.brand }">
              <el-option v-for="item in brandOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
            </el-select>
            <el-select v-model="filterForm.certificateType" placeholder="请选择师训类型" required filterable last-level size="small" style="width: 150px; margin-right: 8px;" @change="handleFilterChange" :class="{ 'is-error': !filterForm.certificateType }">
              <el-option-group v-for="group in certificateTemplateOptions" :key="group.id" :label="group.fullName">
                <el-option v-for="item in group.children" :key="item.id" :label="item.fullName" :value="item.enCode" />
              </el-option-group>
            </el-select>
            <el-select v-model="filterForm.campusStage" placeholder="请选择校区阶段" size="small" style="width: 120px; margin-right: 8px;" @change="handleCampusStageChange">
              <el-option label="全部阶段" value="" />
              <el-option v-for="item in campusStageOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode" />
            </el-select>
            <div v-if="!filterForm.brand || !filterForm.certificateType" class="validation-tip">
              <i class="el-icon-warning" style="color: #f56c6c; margin-right: 4px;"></i>
              <span style="color: #f56c6c; font-size: 12px;">请选择具体的品牌和师训类型</span>
            </div>

            <el-button size="small" icon="el-icon-refresh" :loading="loading" @click="refreshData">刷新</el-button>
          </div>
        </div>
        <div v-loading="loading" class="training-content">
          <!-- 左右横排布局：校区统计和老师统计 -->
          <div class="training-tables-container">
            <!-- 左侧：校区参训统计 -->
            <div class="training-table-section left-section">
              <!-- 按证书类型分组的统计数据 -->
              <div v-if="groupedData && groupedData.certificateTypeGroups && groupedData.certificateTypeGroups.length > 0">
                <div v-for="group in groupedData.certificateTypeGroups" :key="group.certificateTypeId" class="training-group-item">
                  <div class="training-section">
                    <h4 class="section-title">{{ group.certificateTypeName }}统计</h4>
                    <el-table :data="group.regionStatistics" size="small" stripe border class="report-table training-table">
                      <el-table-column prop="regionName" label="管理区域" width="120" align="center">
                        <template slot-scope="scope">
                          <span class="data-primary">{{ scope.row.regionName }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="totalCampusCount" label="校区总数" width="100" align="center">
                        <template slot-scope="scope">
                          <span class="data-info">{{ scope.row.totalCampusCount || 0 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="participatedCampusCount" label="参训校区数" width="110" align="center">
                        <template slot-scope="scope">
                          <span class="data-success">{{ scope.row.participatedCampusCount || 0 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="unparticipatedCampusCount" label="未参训校区数" width="120" align="center">
                        <template slot-scope="scope">
                          <span class="data-warning">{{ scope.row.unparticipatedCampusCount || 0 }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="participationRate" label="参训率" width="100" align="center">
                        <template slot-scope="scope">
                          <span :class="getCertificateRateClass(scope.row.participationRate)">{{ (scope.row.participationRate || 0).toFixed(2) }}%</span>
                        </template>
                      </el-table-column>
                    </el-table>

                    <!-- 总计行 -->
                    <div class="summary-row">
                      <el-table :data="[group.summary]" size="small" border class="report-table summary-table">
                        <el-table-column label="总计" width="120" align="center">
                          <template>
                            <span class="data-info">总计</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="totalCampusCount" label="" width="100" align="center">
                          <template slot-scope="scope">
                            <span class="data-info">{{ scope.row.totalCampusCount || 0 }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="totalParticipatedCampusCount" label="" width="110" align="center">
                          <template slot-scope="scope">
                            <span class="data-success">{{ scope.row.totalParticipatedCampusCount || 0 }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="totalUnparticipatedCampusCount" label="" width="120" align="center">
                          <template slot-scope="scope">
                            <span class="data-warning">{{ scope.row.totalUnparticipatedCampusCount || 0 }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="totalParticipationRate" label="" width="100" align="center">
                          <template slot-scope="scope">
                            <span :class="getCertificateRateClass(scope.row.totalParticipationRate)">{{ (scope.row.totalParticipationRate || 0).toFixed(2) }}%</span>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 原有的校区参训统计（兼容性保留） -->
              <div v-else-if="data.campusStatistics && data.campusStatistics.length > 0" class="training-section">
                <h4 class="section-title">结业校区数量统计</h4>
                <el-table :data="data.campusStatistics" size="small" stripe border show-summary :summary-method="getCampusSummaries" sum-text="总计" class="report-table training-table">
                  <el-table-column prop="regionName" label="区域名称" min-width="120" align="center">
                    <template slot-scope="scope">
                      <span class="data-primary">{{ scope.row.regionName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="totalCampusCount" label="校区总数" min-width="100" align="center">
                    <template slot-scope="scope">
                      <span class="data-info">{{ scope.row.totalCampusCount || 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="certifiedCampusCount" label="获证校区数" min-width="110" align="center">
                    <template slot-scope="scope">
                      <span class="data-success">{{ scope.row.certifiedCampusCount || 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="uncertifiedCampusCount" label="未获证校区数" min-width="120" align="center">
                    <template slot-scope="scope">
                      <span class="data-warning">{{ scope.row.uncertifiedCampusCount || 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="campusCertificationRate" label="校区获证率" min-width="110" align="center">
                    <template slot-scope="scope">
                      <span :class="getCertificateRateClass(scope.row.campusCertificationRate)">{{ (scope.row.campusCertificationRate || 0).toFixed(2) }}%</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>

            <!-- 右侧：老师参训统计 -->
            <div class="training-table-section right-section">
              <div class="training-section">
                <h4 class="section-title">结业老师数量统计</h4>
                <el-table :data="data.teacherStatistics" size="small" stripe border show-summary :summary-method="getTeacherSummaries" sum-text="总计" class="report-table training-table">
                  <el-table-column prop="regionName" label="区域名称" min-width="120" align="center">
                    <template slot-scope="scope">
                      <span class="data-primary">{{ scope.row.regionName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="totalTeacherCount" label="参训老师总数" min-width="120" align="center">
                    <template slot-scope="scope">
                      <span class="data-info">{{ scope.row.totalTeacherCount || 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="certifiedTeacherCount" label="获证老师数" min-width="110" align="center">
                    <template slot-scope="scope">
                      <span class="data-success">{{ scope.row.certifiedTeacherCount || 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="uncertifiedTeacherCount" label="未获证老师数" min-width="120" align="center">
                    <template slot-scope="scope">
                      <span class="data-warning">{{ scope.row.uncertifiedTeacherCount || 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="teacherCertificationRate" label="老师获证率" min-width="110" align="center">
                    <template slot-scope="scope">
                      <span :class="getCertificateRateClass(scope.row.teacherCertificationRate)">{{ (scope.row.teacherCertificationRate || 0).toFixed(2) }}%</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
import { getCampusTrainingStatistics } from '@/api/report/branch'
import { DICTIONARY_TYPES, getEnabledDictionaryData } from '@/utils/dictionaryConstants'

export default {
  name: 'TrainingStatisticsReport',
  props: {
    // 品牌选项
    brandOptions: {
      type: Array,
      default: () => []
    },
    // 证书模板选项
    certificateTemplateOptions: {
      type: Array,
      default: () => []
    },
    // 管理区域选项
    managementAreaOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      areaSortOrder: 'asc', // 管理区域排序顺序：'asc' 升序，'desc' 降序
      data: {
        campusStatistics: [],
        teacherStatistics: []
      },
      groupedData: {
        certificateTypeGroups: []
      },

      certificateTypes: [],
      campusStageOptions: [], // 校区阶段选项
      filterForm: {
        startDate: '',
        endDate: '',
        brand: 'bell', // 默认贝尔安亲
        certificateType: 'teacher', // 默认老师岗位培训
        campusStage: '' // 校区阶段
      }
    }
  },
  computed: {
    // 日期范围计算属性
    dateRange: {
      get() {
        if (this.filterForm.startDate && this.filterForm.endDate) {
          return [this.filterForm.startDate, this.filterForm.endDate]
        }
        return []
      },
      set(value) {
        if (value && value.length === 2) {
          this.filterForm.startDate = value[0]
          this.filterForm.endDate = value[1]
        } else {
          this.filterForm.startDate = ''
          this.filterForm.endDate = ''
        }
      }
    }
  },
  watch: {
    certificateTemplateOptions: {
      handler() {
        if (this.certificateTemplateOptions.length > 0) {
          this.setDefaultCertificateType()
        }
      },
      immediate: true
    }
  },
  mounted() {
    // 组件挂载时自动加载数据，使用默认的品牌和师训类型
    this.loadCampusStageOptions()
    this.loadTrainingData()
  },
  methods: {
    // 加载校区阶段选项
    async loadCampusStageOptions() {
      try {
        this.campusStageOptions = await getEnabledDictionaryData(DICTIONARY_TYPES.CAMPUS_LEVEL)
      } catch (error) {
        console.error('加载校区阶段选项失败:', error)
        this.campusStageOptions = []
      }
    },

    // 处理日期范围变化
    handleDateRangeChange(value) {
      if (value && value.length === 2) {
        this.filterForm.startDate = value[0]
        this.filterForm.endDate = value[1]
      } else {
        this.filterForm.startDate = ''
        this.filterForm.endDate = ''
      }
      this.handleFilterChange()
    },

    // 加载校区参训统计数据
    async loadTrainingData() {
      // 验证必填筛选条件
      if (!this.filterForm.brand || !this.filterForm.certificateType) {
        // 如果没有选择具体的品牌和师训类型，清空数据并显示提示
        this.data = {
          campusStatistics: [],
          teacherStatistics: []
        }
        this.groupedData = {
          certificateTypeGroups: []
        }

        if (!this.filterForm.brand && !this.filterForm.certificateType) {
          this.$message.warning('请选择具体的品牌和师训类型后查询')
        } else if (!this.filterForm.brand) {
          this.$message.warning('请选择具体的校区品牌')
        } else if (!this.filterForm.certificateType) {
          this.$message.warning('请选择具体的师训类型')
        }
        return
      }

      this.loading = true
      try {
        // 构建查询参数
        const params = {}

        // 日期范围为空时查询所有数据，不再验证日期范围
        if (this.filterForm.startDate) {
          params.startDate = this.filterForm.startDate
        }

        if (this.filterForm.endDate) {
          params.endDate = this.filterForm.endDate
        }
        if (this.filterForm.company) {
          params.company = this.filterForm.company
        }

        // 必须传递具体的筛选条件
        params.certificateType = this.filterForm.certificateType
        params.brand = this.filterForm.brand
        params.campusStage = this.filterForm.campusStage

        // 构建查询参数

        // 调用校区参训统计接口
        const response = await getCampusTrainingStatistics(params)
        const responseData = response.data || response
        // 处理API返回数据

        // 处理返回的统计数据
        // 原始返回数据处理

        // 对校区统计数据按管理区域排序
        const sortedCampusStatistics = this.sortRegionData(responseData.campusStatistics || [])
        // 对老师统计数据按管理区域排序
        const sortedTeacherStatistics = this.sortRegionData(responseData.teacherStatistics || [])

        this.data = {
          campusStatistics: sortedCampusStatistics,
          teacherStatistics: sortedTeacherStatistics
        }

        // 保持兼容性，初始化分组数据为空
        this.groupedData = {
          certificateTypeGroups: []
        }

        // 通知父组件数据已更新
        this.$emit('data-updated', {
          data: this.data,
          groupedData: this.groupedData
        })
      } catch (error) {
        this.$message.error('校区参训统计数据加载失败')
        console.error('校区参训统计数据加载错误:', error)

        // 初始化空数据
        this.data = {
          campusStatistics: [],
          teacherStatistics: []
        }
        this.groupedData = {
          certificateTypeGroups: []
        }
      } finally {
        this.loading = false
      }
    },

    // 不再设置默认证书类型，强制用户手动选择
    setDefaultCertificateType() {
      // 移除默认值设置逻辑，用户必须手动选择具体的师训类型
      // 这样确保用户明确知道自己选择的筛选条件
    },

    // 获取证书率标签类型
    getCertificateRateTagType(rate) {
      const numRate = Number(rate || 0)
      if (numRate >= 80) {
        return 'success' // 绿色：获证率>=80%
      } else if (numRate >= 60) {
        return 'warning' // 橙色：获证率60%-79%
      } else {
        return 'danger' // 红色：获证率<60%
      }
    },

    // 获取证书率样式类
    getCertificateRateClass(rate) {
      const numRate = Number(rate || 0)
      if (numRate >= 80) {
        return 'data-success' // 绿色：获证率>=80%
      } else if (numRate >= 60) {
        return 'data-warning' // 橙色：获证率60%-79%
      } else {
        return 'data-danger' // 红色：获证率<60%
      }
    },

    // 获取校区统计总计
    getCampusSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          if (column.property === 'campusCertificationRate') {
            // 计算平均获证率
            const totalCampus = data.reduce((sum, item) => sum + (Number(item.totalCampusCount) || 0), 0)
            const certifiedCampus = data.reduce((sum, item) => sum + (Number(item.certifiedCampusCount) || 0), 0)
            const avgRate = totalCampus > 0 ? (certifiedCampus / totalCampus) * 100 : 0
            sums[index] = avgRate.toFixed(2) + '%'
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },

    // 获取老师统计总计
    getTeacherSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          if (column.property === 'teacherCertificationRate') {
            // 计算平均获证率
            const totalTeacher = data.reduce((sum, item) => sum + (Number(item.totalTeacherCount) || 0), 0)
            const certifiedTeacher = data.reduce((sum, item) => sum + (Number(item.certifiedTeacherCount) || 0), 0)
            const avgRate = totalTeacher > 0 ? (certifiedTeacher / totalTeacher) * 100 : 0
            sums[index] = avgRate.toFixed(2) + '%'
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },

    // 处理筛选条件变化
    handleFilterChange() {
      this.loadTrainingData()
      this.$emit('filter-change', this.filterForm)
    },

    // 处理校区阶段变化
    handleCampusStageChange() {
      this.loadTrainingData()
      this.$emit('filter-change', this.filterForm)
    },

    // 刷新数据
    refreshData() {
      this.loadTrainingData()
      this.$emit('refresh')
    },

    // 获取区域排序值
    getRegionSort(regionName) {
      if (!this.managementAreaOptions || !regionName) return 999
      const region = this.managementAreaOptions.find(item => item.fullName === regionName)
      const sortCode = region ? region.sortCode || 999 : 999
      // 强制转换为数字类型
      const numericSortCode = Number(sortCode)
      // 强制转换为数字类型
      return isNaN(numericSortCode) ? 999 : numericSortCode
    },

    // 对区域数据进行排序
    sortRegionData(data) {
      if (!data || !Array.isArray(data)) return []

      const sortedData = [...data].sort((a, b) => {
        const sortA = this.getRegionSort(a.regionName)
        const sortB = this.getRegionSort(b.regionName)

        if (this.areaSortOrder === 'asc') {
          return sortA - sortB
        } else {
          return sortB - sortA
        }
      })

      return sortedData
    }
  }
}
</script>

<style scoped>
@import './shared-table-styles.scss';
</style>
